package com.token;

import com.admin.entity.Admin;
import com.admin.service.IAdminService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

@Component
public class LoginRealm extends AuthorizingRealm {
    @Autowired
    private IAdminService iadminService;

    @Override
    public boolean supports(AuthenticationToken authenticationToken) {
        return authenticationToken instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        String tokenString = principalCollection.toString();
        String username = JwtUtil.getUsername(tokenString);
        List<String> strs = iadminService.getPermissionByUsername(username);
        strs.removeAll(Collections.singleton(null));
        simpleAuthorizationInfo.addStringPermissions(strs);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getPrincipal();
        String username = JwtUtil.getUsername(token);
        Admin admin = iadminService.getAdminByUserName(username);
        if (admin == null) {
            throw new RuntimeException("令牌无效");
        }
        return new SimpleAuthenticationInfo(token, token, getName());
    }
}
